/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.losalpes.persistence;

import com.losalpes.persistence.entity.Compra;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 *
 * @author Juan Ma
 */
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ComprasPersistenceServices implements IComprasPersistenceServices {

    @PersistenceContext
    private EntityManager em;

    @Resource
    UserTransaction ut;

    @Resource(mappedName="jdbc/tiendalosalpesext")
    DataSource dataSource;

    public void initTransaction(){
        try {
            ut.begin();
        } catch (NotSupportedException ex) {
            Logger.getLogger(ComprasPersistenceServices.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SystemException ex) {
            Logger.getLogger(ComprasPersistenceServices.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void commitTransaction(){
        try {
            if(ut.getStatus() != Status.STATUS_ROLLEDBACK){
                ut.commit();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            try{
                ut.rollback();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    public void rollBackTransaction(){
        try {
            ut.rollback();
        } catch (Exception ex) {
            Logger.getLogger(ComprasPersistenceServices.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }
    
    public void create(Object compra){
        initTransaction();
        em.persist(compra);
        commitTransaction();
    }

    public void update(Object compra){
        initTransaction();
        em.merge(compra);
        commitTransaction();
    }

    public void delete(Object compra){
        initTransaction();
        em.remove(compra);
        commitTransaction();
    }

    public List findAll(Class c) {
        return em.createQuery("select O from " + c.getSimpleName() + " as O").getResultList();
    }

    private void insertRemoteDatabase (Compra compra) throws Exception{
        Connection conn = dataSource.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement pstmt = conn.prepareStatement("SELECT SALDO FROM TARJETA_CLIENTE WHERE ID_CLIENTE = ?");
        pstmt.setString(1, compra.getCliente().getNumeroDocumento());
        ResultSet rs = pstmt.executeQuery();
        if(rs.next()){
            Double saldo = rs.getDouble("SALDO");
            if(saldo.doubleValue() >= compra.obtenerPrecioTotal()){
                pstmt = conn.prepareStatement("UPDATE TARJETA_CLIENTE SET SALDO = ? WHERE ID_CLIENTE = ?");
                pstmt.setDouble(1, saldo.doubleValue() - compra.obtenerPrecioTotal());
                pstmt.setString(2, compra.getCliente().getNumeroDocumento());
                pstmt.executeUpdate();
            }else{
                throw new Exception("Saldo Insuficiente");
            }
        }else{
            throw new Exception("El cliente no tiene asociada una tarjeta");
        }
    }

    public void registrarCompra(Compra compra) throws Exception{
        try {
            initTransaction();
            em.persist(compra);
            insertRemoteDatabase(compra);
            commitTransaction();
        } catch (Exception ex) {
            Logger.getLogger(ComprasPersistenceServices.class.getName()).log(Level.SEVERE, null, ex);
            rollBackTransaction();
            throw ex;
        }
    }
 
}
